let user = {
    username: "admin1",
    password: "12345"
};

let fs = require("fs");
let path = require("path");
let http = require("http");

let server = http.createServer((req, res) => {
    res.writeHead(200, {
        "content-type": "text/html;charset=utf-8"
    });
    let requrl = req.url;
    if (requrl == "/login") {
        res.writeHead(200, {
            "content-type": "text/html;charset=utf-8"
        });
        let pathurl = path.join(__dirname, "/persons.json");
        let data = fs.readFileSync(pathurl);
        let arr = JSON.parse(data.toString())
        let username = arr.find((item) => {
            return item.username == user.username && item.password == user.password
        })
        if (username) {
            console.log("登录成功")
        } else {
            console.log("用户名和密码错误")
        }
        res.end();
    } else if (requrl == "/reg") {
        res.writeHead(200, {
            "content-type": "text/html;charset=utf-8"
        });
        let pathurl = path.join(__dirname, "persons.json");
        let data = fs.readFileSync(pathurl);
        let arr = JSON.parse(data.toString());
        let reg = arr.findIndex((item) => {
            return item.username == user.username && item.password == user.password
        })

        if (reg == -1) {
            arr.push(user);
            console.log("注册成功");
            fs.writeFileSync(__dirname + "/persons.json", JSON.stringify(arr));
        } else {
            console.log("该用户已被注册")
        }
        res.end();
    } 
})

server.listen(3000, "127.0.0.1", () => {
    console.log("服务启动");
})